<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/27
 * Time: 14:40
 */

namespace App\Api\Admin\Controllers;
use App\Exceptions\ApiException;
use App\Models\Branch;
use Illuminate\Http\Request;
use App\Models\AdminUser;
use App\Models\Shareholder;
use App\Models\ShareholderLog;
use App\Models\Admin\Log;
use App\Models\MemberShip;
use App\Models\User;
use Excel;
use App\Models\Admin\Role;
use App\Models\AuditShareholdersFunds;
use App\Services\Cooperation;
use Illuminate\Support\Facades\DB;

class ManageController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

    }

    public function index(Request $request)
    {
        $page = intval($request->input('page')) ?: 1;
        $name = IT('name');
        $mobile = IT('mobile');
        $page = $page - 1;
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ? : 10;
        $where = [];
        if ($name) {
            $where[] = ['username', 'like', '%' . $name . '%'];
        }
        if ($mobile) {
            $where[] = ['mobile', 'like', '%' . $mobile . '%'];
        }

        $user_list = AdminUser::where($where)->where('is_delete',0)->orderBy('id', 'desc')->paginate($pagesize);

        $list_data = [];
        foreach ($user_list as $item){
            $temp_arr = [];
            $role_info = [];
            if($item->role_id) {
                $role_info = Role::where(['id' => $item->role_id])->first();
            }
            $city_origin = D('affiliation')->where('id',$item->city_of_origin)->value('locality_name');
            $temp_arr['city_origin']= empty($city_origin) ? '' : $city_origin;
            $temp_arr['city_origin_id']= $item->city_of_origin;
            $temp_arr['id'] = $item->id;
            $temp_arr['username'] = $item->name;
            $temp_arr['password'] = $item->password;
            $temp_arr['role_id'] = $item->role_id;
            $temp_arr['role_name'] = empty($role_info) ? '' : $role_info->name;
            $temp_arr['mobile'] = $item->mobile;
            $list_data[] = $temp_arr;
        }
        
        return json_success('ok',['total'=>$user_list->total(),'totalPage' => $user_list->lastPage(),'list' => $list_data ]);
    }

    /**
     * @return array
     * 结算管理员下拉列表
     */

    public function  ManagerList()
    {
        $user_list = AdminUser::where('is_delete',0)->orderBy('id', 'asc')->get();
        $list_data = [];
        foreach ($user_list as $item){
            $temp_arr = [];
            $temp_arr['id'] = $item->id;
            $temp_arr['username'] = $item->name;
            $temp_arr['role_id'] = $item->role_id;
            $list_data[] = $temp_arr;
        }
        return json_success('ok',['list' => $list_data ]);

 }
    /**
     * 添加管理员
     * @return array
     * @throws ApiException
     */
    public function AddUser()
    {
        $ascription = IT('ascription',true,'请填写归属地');
        $username = IT('username', true, '请填写用户名');
        $password = IT('password', true, '请填写密码');
        $role_id = IT('role_id', true, '请选择用户的角色');
        $mobile = IT('mobile', true, '请填写手机号码');
        if(!preg_match("/^\\d{11}$/",$mobile)){
            return  json_error('手机号必须为11位数字');
        }
        $avatar = IT('avatar');
        $check_name = AdminUser::where(['username' => $username,'is_delete'=> 0])->first(['id']);
        if($check_name){
            return json_error('用户名已存在');
        }
        $check_mobile = AdminUser::where(['mobile' => $username,'is_delete'=> 0])->first(['id']);
        if($check_mobile){
            return json_error('手机号已存在');
        }
        if(!ctype_digit($ascription)){
            return json_error('归属地请输入对应的城市id');
         }
        // 判断角色是否存在
        if(!Role::find($role_id)) {
            return json_error('选择的角色不存在');
        }

        $data = [
            'username' =>$username,
            'password' =>MD5($password),
            'role_id' =>$role_id,
            'name' =>$username,
            'mobile' =>$mobile,
            'avatar' =>$avatar,
            'city_of_origin'=>$ascription,
            'encrypt' => str_random(8),
            'created_at' => time2date(),
        ];
        $id = AdminUser::insertGetId($data);
        if ($id) {
             (new Log)->add($this->user, '添加用户' . $username . ', id为' . $id . '');
             return json_success('ok');
            }else {
             return json_error('添加用户失败');
        }
    }

    /**
     * 修改管理员名称和密码
     * @return array
     * @throws ApiException
     */
    public function ModifyUser()
    {
        $user_id = IT('id', true, '请填写用户ID');
        $ascription = IT('ascription');
        $username = IT('username');
        $password = IT('password');
        $mobile = IT('mobile');
        $role_id = IT('role_id');
        $modifuser = AdminUser::find($user_id);
        if(!$modifuser){
            return json_error('该用户不存在');
        }
        if(!empty($username) && $username !== $modifuser->username){
            $modifydata['username'] = $username;
            $modifydata['name'] = $username;
        }
        if(!empty($ascription) && $ascription !== $modifuser->city_of_origin){
    /*        if(!ctype_digit($ascription)){
                return json_error('归属地请输入对应的城市id');
            }*/
            $modifydata['city_of_origin'] = $ascription;
        }
        if(!empty($password) && MD5($password) !==$modifuser->username ){
            $modifydata['password'] = MD5($password);
        }
        if(!empty($mobile) && $mobile!==$modifuser->mobile){
            $modifydata['mobile'] = $mobile;
        }
        if(!empty($role_id) && $role_id!==$modifuser->role_id){
            $modifydata['role_id'] = $role_id;
        }
        $modifydata['encrypt'] =  str_random(8);
        $modifydata['updated_at'] = time2date();
        if ($this->user['permissions'] == '*') {
            if ($modifuser) {
                $user = AdminUser::where('id',$user_id)->update($modifydata);
                if ($user) {
                    (new Log)->add($this->user, '修改了管理员' . $username . ', id为' . $user_id . '');
                    return json_success('ok');
                } else {
                    return json_error('修改失败');
                }
            }
        } else {
            throw new ApiException('你没有权限修改', 0);
        }
    }

    /**
     * 删除管理员
     */
    public function  DelManage(){
        $user_id = IT('id', true, '请填写用户ID');
        $check_name = AdminUser::where(['id'=>$user_id, 'is_delete'=>0])->first();
        if(!$check_name){
            return json_error('该用户不存在');
        }
       $del= AdminUser::where('id',$user_id)->update(['is_delete'=>1]);
        if($del){
            (new Log)->add($this->user, '删除了管理员' . $check_name->username . ', id为' . $user_id . '');
            return json_success('ok');
        }else{
            return json_error('删除失败');
        }

    }

    /**
     *管理员详情
     *
     */
    public function ManageDetails(){
        $user_id = IT('id', true, '请填写用户ID');
        $user_data = AdminUser::where(['id'=>$user_id, 'is_delete'=>0])->first();
        if(empty($user_data)) {
            return json_error('该用户不存在');
        }

        $city_origin = D('affiliation')->where('id',$user_data['city_of_origin'])->value('locality_name');
        $temp_arr['city_origin']= empty($city_origin) ? '' : $city_origin;
        $temp_arr['city_origin_id']= $user_data['city_of_origin'];
        $temp_arr['id']= $user_data['id'];
        $temp_arr['username']= $user_data['name'];
        $temp_arr['password']= $user_data['password'];
        $temp_arr['role_id']= $user_data['role_id'];
        $temp_arr['mobile']= $user_data['mobile'];
        $list_data = $temp_arr;
        return json_success('ok',$list_data);

    }

   /**
   *股东用户列表
   *
   */
     public function AdminShareholderList(Request $request){
         $uase_city_of_origin = $this->user['city_of_origin'];
         $role_id = $this->user['role_id'];
         $TotalStock = config('admin.TotalStock');//总注册资金
         $page = intval($request->input('page')) ?: 1;
         $mobile = IT('mobile');//手机号码
         $username = IT('username');//用户名称
         $residence = IT('residence'); //现居城市
         $ascription= IT('ascription');//股东归属分公司
         $startdate = IT('startdate'); //开始时间
         $enddate = IT('enddate'); //结束时间
         $pageSize = IT('pagesize') ?: 10;
         $where = [];
         $where['status'] = 0;
         $where['data_audit'] = 1;
         $where['fund_audit'] = 1;
         if($role_id == 5 ){
             $where['user_binding'] = $this->user['id'];
         }
         $pageSize = IT('pagesize') ?: 10;
         //  $behavior= IT('behavior');
         /* if($behavior=='data_audit'){
              $where =[ 'status'=> 0, 'data_audit'=>$Audit_status ];
          }
          if($behavior=='stock_audit'){
              $where =[ 'status'=> 0, 'stock_audit'=>$Audit_status ];
          }*/
         $lists = Shareholder::where(function($query) use($ascription,$mobile,$username,$residence,$startdate,$enddate) {
             if(!empty($mobile)){
                 $query->where('mobile','like','%'.$mobile. '%');
             } else if (!empty($username) ) {
                 $query->where('user_name','like','%' .$username. '%');
             } else if(!empty($residence)) {
                 $query->where('residence', 'like', '%' . $residence . '%');
             } else if(!empty($ascription)){
                 $query->where('ascription','=',$ascription);
             } else if(!empty($startdate) && !empty($enddate) ) {
                 $query->whereBetween('arrival_account',[$startdate, $enddate]);
             }
         })->where($where)->orderBy('id', 'desc')->paginate($pageSize);
         
         $temp_arr = [];
         $list_data = [];
         foreach ($lists as &$key) {
             $ascription = D('affiliation')->where('id',$key->ascription)->value('locality_name');
             $temp_arr['id'] = $key->id;
             $temp_arr['ascription'] = empty($ascription) ? '' : $ascription; //用户归属的运营中心
             $temp_arr['ascription_id'] = $key->ascription; //用户归属的运营中心
             $temp_arr['user_type'] = '股东用户';
             $temp_arr['user_name'] = $key->user_name;
             $temp_arr['sex'] = $key->sex;
             $temp_arr['Birthday'] = $key->Birthday;
             $temp_arr['mobile'] = $key->mobile;
             $temp_arr['share'] = $key->share;
             $temp_arr['bank_name'] = $key->bank_name;
             $temp_arr['opening_bank'] = $key->opening_bank;
             $temp_arr['account_name'] = $key->account_name; //账户名
             $temp_arr['bank_number'] = $key->bank_number; //银行卡号
             $temp_arr['id_card'] = $key->id_card; //身份证号
             $temp_arr['residence'] = $key->residence; //现居住地
             $temp_arr['address'] = $key->address; //身份证地址
             $temp_arr['total_funds'] = $key->total_funds;
             $temp_arr['created_at'] = empty($key->created_at) ? '' : $key->created_at;
             $temp_arr['updated_at'] = empty($key->updated_at) ? '': $key->updated_at;
             $temp_arr['ratio']  = $key->share/$TotalStock;
             $temp_arr['certificate_number'] = $key->certificate_number;
             $temp_arr['arrival_account'] = substr($key->arrival_account,0,10);
             $temp_arr['shareholder_agree_img'] = empty($key->shareholder_agree_img) ?  0 : 1;
             $temp_arr['operator'] = $key->operator;//操作人
             $temp_arr['referrer'] = $key->referrer ?? '';
             $temp_arr['referrer_mobile'] = $key->referrer_mobile ?? '';
             $list_data[] = $temp_arr;
         }
         unset($key);
         $Total_shares = Shareholder::where(function($query) use($mobile,$username,$residence,$startdate,$enddate) {
             if(!empty($mobile)){
                 $query->where('mobile','like','%'.$mobile. '%');
             } else if (!empty($username) ) {
                 $query->where('user_name','like','%' .$username. '%');
             } else if(!empty($residence)) {
                 $query->where('residence', 'like', '%' . $residence . '%');
             }else if(!empty($startdate) && !empty($enddate) ) {
                 $query->whereBetween('arrival_account',[$startdate, $enddate]);
             }
         })->where($where)->sum('share');
         $Total_funds = Shareholder::where(function($query) use($mobile,$username,$residence,$startdate,$enddate) {
             if(!empty($mobile)){
                 $query->where('mobile','like','%'.$mobile. '%');
             } else if (!empty($username) ) {
                 $query->where('user_name','like','%' .$username. '%');
             } else if(!empty($residence)) {
                 $query->where('residence', 'like', '%' . $residence . '%');
             } else if(!empty($startdate) && !empty($enddate) ) {
                 $query->whereBetween('arrival_account',[$startdate, $enddate]);
             }
         })->where($where)->sum('total_funds');
         return json_success('ok',['total'=>$lists->total(),'totalPage' => $lists->lastPage(), 'list' => $list_data,'Total_shares'=>$Total_shares,'Total_funds'=>$Total_funds]);
     }
    /**
     * 股东用户导出excel
     *
     */
    public function ShareholderExport(){
        $TotalStock = config('admin.TotalStock');//总注册资金
        $uase_city_of_origin = $this->user['city_of_origin'];
        $mobile = IT('mobile');//手机号码
        $username = IT('username');//用户名称
        $residence = IT('residence'); //现居城市
        $ascription= IT('ascription');//股东归属分公司
        $startdate = IT('startdate'); //开始时间
        $enddate = IT('enddate'); //结束时间
        $where = [ ];
        if($uase_city_of_origin !== 0 ){
            $where =[ 'status'=> 0, 'ascription'=> $uase_city_of_origin  ];
        }else{
            $where =[ 'status'=> 0];
        }
        $where['data_audit'] = 1;
        $where['fund_audit'] = 1;
        $Shareholder_data = Shareholder::where(function($query) use($ascription,$mobile,$username,$residence,$startdate,$enddate) {
            if(!empty($mobile)){
                $query->where('mobile','like','%'.$mobile. '%');
            } else if (!empty($username) ) {
                $query->where('user_name','like','%' .$username. '%');
            } else if(!empty($residence)) {
                $query->where('residence', 'like', '%' . $residence . '%');
            } else if(!empty($ascription)){
                $query->where('ascription','=',$ascription);
            } else if(!empty($startdate) && !empty($enddate) ) {
                $query->whereBetween('arrival_account',[$startdate, $enddate]);
            }
        })->where($where)->orderBy('id', 'desc')->get();
        $temp_arr = [];
        $list_data = [];
        foreach ($Shareholder_data as &$key) {
            $ascription = D('affiliation')->where('id',$key->ascription)->value('locality_name');
            $temp_arr['id'] = $key->id;
            $temp_arr['ascription'] = empty($ascription) ? '' : $ascription; //用户归属的运营中心
            $temp_arr['user_type'] = '股东用户';
            $temp_arr['user_name'] = $key->user_name;
            $temp_arr['sex'] = $key->sex;
            $temp_arr['Birthday'] = $key->Birthday;
            $temp_arr['mobile'] = $key->mobile;
            $temp_arr['share'] = (int)$key->share;
            $temp_arr['bank_name'] = $key->bank_name;
            $temp_arr['opening_bank'] = $key->opening_bank;
            $temp_arr['account_name'] = $key->account_name; //账户名
            $temp_arr['bank_number'] = $key->bank_number; //银行卡号
            $temp_arr['id_card'] = $key->id_card; //身份证号
            $temp_arr['residence'] = $key->residence; //现居住地
            $temp_arr['address'] = $key->address; //身份证地址
            $temp_arr['total_funds'] =(int) $key->total_funds;
            $temp_arr['created_at'] = empty($key->created_at) ? '' : $key->created_at;
            $temp_arr['updated_at'] = empty($key->updated_at) ? '': $key->updated_at;
            $temp_arr['ratio']  = $key->share/$TotalStock;
            $temp_arr['certificate_number'] = $key->certificate_number;
            $temp_arr['arrival_account'] = $key->arrival_account ?? '' ;
            $temp_arr['operator'] = $key->operator;//操作人
            $temp_arr['referrer'] = $key->referrer ?? '';
            $temp_arr['referrer_mobile'] = $key->referrer_mobile ?? '';
            $list_data[] = $temp_arr;
        }
        (new Log)->add($this->user, '导出了股东excel表格');
        return json_success('ok',['list'=>$list_data,]);
      /*
        $export_arr = array();
            $export_arr[0]['name'] = trans("Shareholder.Shareholder.name");
            $export_arr[0]['sex'] = trans("Shareholder.Shareholder.sex");
            $export_arr[0]['Birthday'] = trans("Shareholder.Shareholder.Birthday");
            $export_arr[0]['mobile'] = trans("Shareholder.Shareholder.mobile");
            $export_arr[0]['share'] = trans("Shareholder.Shareholder.share");
            $export_arr[0]['total_funds'] = trans("Shareholder.Shareholder.total_funds");
            $export_arr[0]['ratio'] = trans("Shareholder.Shareholder.filter_placeholder");
            $export_arr[0]['created_at'] = trans("Shareholder.Shareholder.created_at");
            $export_arr[0]['certificate_number'] = trans("Shareholder.Shareholder.certificate_number");
            foreach($Shareholder_data as $key=>$val) {
                $export_arr[$key + 1]['name'] = $val->user_name;
                $export_arr[$key + 1]['sex'] = $val->sex;
                $export_arr[$key + 1]['Birthday'] = $val->Birthday;
                $export_arr[$key + 1]['mobile'] = $val->mobile;
                $export_arr[$key + 1]['share'] = $val->share;
                $export_arr[$key + 1]['total_funds'] = $val->total_funds;
                $export_arr[$key + 1]['ratio']=  $val->share/$TotalStock;
                $export_arr[$key + 1]['created_at']=  $val->created_at;
                $export_arr[$key + 1]['certificate_number']=  $val->certificate_number;
            }
          Excel::create(trans("Shareholder.shareholder_title"), function($excel) use ($export_arr){
                $excel->sheet(trans("Shareholder.shareholder_title"), function($sheet) use ($export_arr){
                    $sheet->setWidth(['A'=>20, 'B'=>20,'C'=>20, 'D'=>20,'E'=>20,'F'=>20, 'G'=>20, 'H'=>20, 'I'=>20,]);
                    $sheet->rows($export_arr);
                });
            })->export('xls');*/
        }

    /**
     * @return array
     * 会员数据导出
     */
     public function MembershipExport(){
         $list= MemberShip::where('status',0)->select('name','mobile','number','sex','admission_fee','bank_number')->get();
        /* foreach($list as $k){
             $k->user_name = $k->name;
             unset($k->name);
         }*/
            (new Log)->add($this->user, '导出了会员excel表格');
            return json_success('ok',$list);
        }

    /**
     * 股东详情
     * @return array
     */
     public function SingleShareholder(){
         $TotalStock = config('admin.TotalStock');//总注册资金
         $id = IT('id',true,'请输入用户id');
         $data = Shareholder::where('id','=',$id)->first();
         $data->ratio = $data['share']/$TotalStock;
         $data->ascription_id = (int)$data['ascription'];
         $data->ascription =  D('affiliation')->where('id',$data['ascription'])->value('locality_name');
         $shareholder_agree_img_list = [];
         if($data->shareholder_agree_img) {
             $shareholder_agree_img_list = explode(',', $data->shareholder_agree_img);
             foreach($shareholder_agree_img_list as &$shareholder_agree_img) {
                 $shareholder_agree_img = file_get_contents(getSignUrl($shareholder_agree_img));
             }
         }
         $data->shareholder_agree_img = $shareholder_agree_img_list;
         return json_success('ok', $data);
     }

    /**
     * 股东股份变更详情
     * @return array
     */
    public function ShareChangeDetails(){
        $TotalStock = config('admin.TotalStock');//总注册资金
        $id = IT('id',true,'请输入用户id');
        $check_audit = AuditShareholdersFunds::where('id','=',$id)->first();
        $data = Shareholder::where('id','=',$check_audit->uid)->first();
        if(!$check_audit){
            return json_error('无此记录');
        }
        $data->ratio = $data['share']/$TotalStock;
        $data->ascription =  D('affiliation')->where('id',$data['ascription'])->value('locality_name');
        $data->ascription_id =  (int)$data['ascription'];
        $data->append_share = AuditShareholdersFunds::where('id','=',$id)->value('append_share');
        $data->dilution_share = AuditShareholdersFunds::where('id','=',$id)->value('dilution_share');
        $data->append_money = AuditShareholdersFunds::where('id','=',$id)->value('append_money');
        return json_success('ok', $data);
    }
     /**
      *股东信息修改
      *
      */
     public function EditShareholder()
    {
        $id = IT('id', true, '请输入ID');
        $user_name = IT('user_name');
        $sex = IT('sex');
        $share = IT('dilution_share');
        $append_share = IT('append_share');
        $share_up = IT('share');
        $ascription = IT('ascription');
        $additional_money =IT('additional_money');//追加钱数
        $Diluted_money =IT('diluted_money');//稀释钱数 暂不做处理
        $mobile = IT('mobile');
        $Birthday = IT('Birthday');
        $total_funds = IT('total_funds');
        $bank_name = IT('bank_name');//银行名称
        $opening_bank = IT('opening_bank'); //开户支行
        $bank_number = IT('bank_number'); //银行卡号
        $id_card = IT('id_card'); //身份证号码
        $residence = IT('residence'); //现在居住的城市
        $address = IT('address'); //身份证地址
        $account_name = IT('account_name'); //开户名
        $certificate_number = IT('certificate_number'); //'请输入证书编号'
        $arrival_account = IT('arrival_account'); //资金到账时间
        $referrer = IT('referrer');//推荐人
        $referrer_mobile= IT('referrer_mobile');//推荐人号码
        $Shareholder_info = Shareholder::where('id', '=', $id)->first();
        $Shareholder_audit = AuditShareholdersFunds::where('uid', '=', $id)->first();
        if(!$Shareholder_info){
            return json_error('用户不存在');
        }
      if($mobile!== $Shareholder_info->mobile ){
          $check_mobile = Shareholder::where(['mobile'=> $mobile,'status'=>0])->first();
          if($check_mobile){
              return json_error('手机号码已存在');
          };
        }
        if ($user_name && ($user_name !== $Shareholder_info->user_name)) {
            $Shareholder_data['user_name'] = $user_name;
        }
        if ($ascription && ($ascription !== $Shareholder_info->ascription)) {
            $Shareholder_data['ascription'] = $ascription;
        }
        if ($sex && ($sex !== $Shareholder_info->sex)) {
            $Shareholder_data['sex'] = $sex;
        }
        if ($bank_name && ($bank_name !== $Shareholder_info->bank_name)) {
            $Shareholder_data['bank_name'] = $bank_name;
        }
        if ($opening_bank && ($opening_bank !== $Shareholder_info->opening_bank)) {
            $Shareholder_data['opening_bank'] = $opening_bank;
        }
        if ($bank_number && ($bank_number !== $Shareholder_info->bank_number)) {
            $Shareholder_data['bank_number'] = $bank_number;
        }
        if ($id_card && ($id_card !== $Shareholder_info->id_card)) {
            $Shareholder_data['id_card'] = $id_card;
        }
        if ($residence && ($residence !== $Shareholder_info->residence)) {
            $Shareholder_data['residence'] = $residence;
        }
        if ($address && ($address !== $Shareholder_info->address)) {
            $Shareholder_data['address'] = $address;
        }
        if ($account_name && ($account_name !== $Shareholder_info->account_name)) {
            $Shareholder_data['account_name'] = $account_name;
        }
        if ($certificate_number && ($certificate_number !== $Shareholder_info->certificate_number)) {
            $Shareholder_data['certificate_number'] = $certificate_number;
        }
        if ($arrival_account && ($arrival_account !== $Shareholder_info->arrival_account)) {
            $Shareholder_data['arrival_account'] = $arrival_account;
        }
      /*  if ($share_up && ($share_up !== $Shareholder_info->share)) {
            $Shareholder_data['share'] = $share_up;
        }*/
        //追加的钱数
        if ($additional_money && ($additional_money !== $Shareholder_info->total_funds)) {
            $audit_insert['append_money']=$additional_money;
        }
        if ($total_funds && ($total_funds !== $Shareholder_info->total_funds)) {
            $Shareholder_data['total_funds']=$total_funds;
        }
        if ($referrer && ($referrer !== $Shareholder_info->referrer)) {
            $Shareholder_data['referrer'] = $referrer;
        }
        if ($referrer_mobile && ($referrer_mobile !== $Shareholder_info->referrer_mobile)) {
            $Shareholder_data['referrer_mobile'] = $referrer_mobile;
        }
        if ((int)$share > 0 || (int)$append_share){
            if((int)$share > 0) {
                $audit_insert['dilution_share'] =$share;
            }
            if((int)$append_share > 0) {
                $audit_insert['append_share']=$append_share;
            }
            //股份变更插入变更记录表
            $audit_insert['uid'] = $id;
            $audit_insert['status'] = 0;
            $audit_insert['created_at'] = time2date();
            AuditShareholdersFunds::insert($audit_insert);
            //股份有变更需要做审核处理
            $Shareholder_data['stock_audit'] = 0;
        }
        if (!empty($mobile) !== $Shareholder_info->mobile ) {
            $Shareholder_data['mobile'] = $mobile;
        }
        if (!empty($Birthday) !== $Shareholder_info->Birthday ) {
            $Shareholder_data['Birthday'] = $Birthday;
        }
        $Shareholder_data['updated_at'] = time2date();
        if($Shareholder_info->data_audit==2){
            $data_audit = 0;
        }else{
            $data_audit =$Shareholder_info->data_audit;
        }
        //股份变更审核不通过，重新提交把状态修改为待审核
      if($Shareholder_info->stock_audit== 2 && !empty($Shareholder_info->stock_no_pass)){
           $Shareholder_data['stock_audit'] = 0;
        }
        $Shareholder_data['data_audit'] = $data_audit;
        //$Shareholder_data['stock_audit'] = $stock_audit;
        $Shareholder_data['operator'] = $this->user['username'];
        $Shareholder_update = Shareholder::where('id', '=', $id)->update($Shareholder_data);

        if ($Shareholder_update && ($Shareholder_info->data_audit == 1) && ($Shareholder_info->fund_audit == 1)) {
            // 股东变更手机号，旧的手机号在用户表不是股东身份,新手机在用户表是股东身份
            if($mobile !== $Shareholder_info->mobile){
                $userRows = User::where([['mobile', '=', $Shareholder_info->mobile]])->first();
                if( $userRows && $userRows->role == 1) {
                    User::where('mobile', '=', $Shareholder_info->mobile)->update(['role' => 0]);
                }
                $userRows = User::where([['mobile', '=', $mobile]])->first();
                if($userRows && $userRows->role != 1){
                    User::where('mobile', '=', $mobile)->update(['role' => 1]);
                }
            }
        }
        (new Log)->add($this->user, '修改了股东' . $user_name . ',的信息-股东id为' . $id . '');
        return json_success('ok');
    }
    /**
     * 添加股东
     * @return array
     * @throws \Exception
     *
     */
     public function AddShareholder(){
         $user_name = IT('user_name',true,'请输入用户名');
         $sex = IT('sex',true,'请输入性别');
         $share = IT('share');
         $mobile = IT('mobile',true,'请输入手机号码');
         $Birthday = IT('Birthday');
         $total_funds = IT('total_funds');
         $bank_name = IT('bank_name');//银行名称
         $opening_bank = IT('opening_bank'); //开户支行
         $bank_number = IT('bank_number'); //银行卡号
         $id_card = IT('id_card'); //身份证号码
         $residence = IT('residence'); //现在居住的城市
         $address = IT('address'); //身份证地址
         $account_name = IT('account_name'); //开户名
         $certificate_number = IT('certificate_number'); //'请输入证书编号'
         $referrer =IT('referrer');//推荐人
         $referrer_mobile =IT('referrer_mobile');//推荐人手机号码
         if($this->user['role_id'] == 5){
             $ascription = $this->user['city_of_origin']; //城市归属地
         }else{
             $ascription = IT('ascription',true,'请填写归属地');
         }
         $user_binding = $this->user['id']; //城市归属地
         $check_mobile = Shareholder::where(['mobile'=>$mobile,'status'=>0])->first();
         if($check_mobile){
            return json_error('手机号已存在');
         }
         if(!preg_match("/^\\d{11}$/",$mobile)){
             return  json_error('手机号必须为11位数字');
         }
         if(!is_numeric($share)){
             return json_error('你的认购份额不是数字类型');
         }
         $data =[
             'user_name'=> $user_name,
             'share'=> $share,
             'mobile'=> $mobile,
             'sex' => $sex,
             'Birthday' => $Birthday,
             'bank_name'=> $bank_name,
             'opening_bank'=> $opening_bank,
             'bank_number'=> $bank_number,
             'id_card'=> $id_card,
             'residence'=> $residence,
             'address'=> $address,
             'account_name'=> $account_name,
             // 'arrival_account'=>$arrival_account,
             'total_funds' => $total_funds,
             'ascription' => $ascription,
             'user_binding' => $user_binding,
             'certificate_number' => $certificate_number,
             'data_audit' => 0,
             'stock_audit' => 0,
             'created_at' => time2date(),
             'referrer' => $referrer,
             'referrer_mobile' => $referrer_mobile,
         ];
         $data= Shareholder::insert($data);
         if($data){
            (new Log)->add($this->user, '添加了股东，姓名-' . $user_name );
            return json_success('ok');
         }else{
             return  json_error('添加失败');
         }
     }

    /**
     * 股东删除
     * @return array
     *
     */
     public function DelShareholder(){
         $id= IT('id',true,'请输入id');
         $user_data = Shareholder::where('id','=',$id)->first();
         $update_data = Shareholder::where('id','=',$id)->update(['status'=> 1]);
         if($update_data){
             User::where('mobile','=',$user_data->mobile)->Update(['role'=> 0]);
             (new Log)->add($this->user, '删除了股东，id-' . $id );
             return json_success('ok');
         }else{
             return json_error('删除失败');
         }
     }

    /**
     * @param Request $request
     * @return array
     * 股金变更日志
     */
     public function ShareholderLgo(Request $request){
         $id= IT('id',true,'请输入id');
         $page = intval($request->input('page')) ?: 1;
         $page = $page - 1;
         $pageSize = IT('pagesize') ?: 10;
         $data = ShareholderLog::where('shareholder_id','=',$id)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get();
         return json_success('ok',$data);
     }
    /**
     * @return array
     * 总注册资金
     */
     public function RegisteredCapital(){
         $data = config('admin.TotalStock');//总注册资金
         return json_success('ok',$data);
     }

     public  function  ShareholderCount(Request $request){
         $TotalStock = config('admin.TotalStock');//总注册资金
         $page = intval($request->input('page')) ?: 1;
         $page = $page - 1;
         $pagesize = IT('pagesize') ?: 10;
         $offset = ($page - 1) * $pagesize;
         $Branch= Branch::where('status',0)->orderBy('id', 'asc')->skip($offset)->take($pagesize)->get();
         $total = Branch::where('status',0)->count();
         $totalPage = ceil($total / $pagesize);
         foreach ($Branch as $key){
            $key->total_number = Shareholder::where(['ascription'=>$key->id,'status'=>0])->count();
            $key->total_limit = Shareholder::where(['ascription'=>$key->id,'status'=>0])->sum('total_funds');
            $key->subscription_ratio = $key->total_limit/$TotalStock;
            unset($key->status);
         }
         return json_success('ok',['total'=>$total,'totalPage' =>$totalPage,'list' => $Branch ]);
     }

    /**
     *股东审核列表
     *
     */
     public function  ShareholderExamine(){
         $TotalStock = config('admin.TotalStock');//总注册资金
         $mobile = IT('mobile');//手机号码
         $username = IT('username');//用户名称
         $startdate = IT('startdate'); //开始时间
         $enddate = IT('enddate'); //结束时间
         $Audit_status = IT('Audit_status',true ,'请填写审核的状态');//审核状态
         $uase_city_of_origin = $this->user['city_of_origin'];
         $role_id = $this->user['role_id'];
         $where_arr = ['status' => 0];
         if($role_id == 5 ){
             $where_arr['user_binding'] = $this->user['id'];
         }
         $pageSize = IT('pagesize') ?: 10;
         $behavior= IT('behavior', true, '请选择审核类型');
         //状态等于1 新增股东通过列表 要资料和资金都通过
         if($Audit_status==1){
             $where_arr['data_audit'] = $Audit_status;
             $where_arr['fund_audit'] = $Audit_status;
         }
        if($behavior=='data_audit') {
              $where_arr['data_audit'] = $Audit_status;
         }
         if($behavior == 'fund_audit') {
             $where_arr['fund_audit'] = $Audit_status;
         }
         if($behavior == 'stock_audit') {
           /*  $where_arr['stock_audit'] = $Audit_status;
             $where_arr['data_audit']=1;
             $where_arr['fund_audit'] =1;*/
             $select = ['audit_shareholders_funds.uid as uid','audit_shareholders_funds.id as id','shareholder.ascription','shareholder.user_name','shareholder.sex','shareholder.Birthday','shareholder.mobile','shareholder.share','shareholder.bank_name','shareholder.opening_bank','shareholder.account_name','shareholder.bank_number','shareholder.id_card',
                 'shareholder.residence','shareholder.address','shareholder.created_at','shareholder.updated_at','shareholder.total_funds','shareholder.certificate_number','shareholder.arrival_account','shareholder.operator','shareholder.data_audit','shareholder.data_no_pass','shareholder.fund_audit','shareholder.fund_no_pass','shareholder.referrer','shareholder.referrer_mobile'];
             $Shareholder_data = AuditShareholdersFunds::where('audit_shareholders_funds.status',$Audit_status)
                 ->where(function($query) use($mobile,$username,$startdate,$enddate) {
                     if(!empty($mobile)){
                         $query->where('shareholder.mobile', '=', $mobile);
                     } else if (!empty($username) ) {
                         $query->where('shareholder.user_name','like','%' .$username. '%');
                     } else if(!empty($startdate) && !empty($enddate) ) {
                         $query->whereBetween('shareholder.arrival_account',[$startdate, $enddate]);
                     }
                 })->leftjoin('shareholder', 'audit_shareholders_funds.uid', '=','shareholder.id')
                 ->select($select)
                 ->orderBy('uid', 'desc')->paginate($pageSize);
         }else{
             $Shareholder_data = Shareholder::where(function($query) use($mobile,$username,$startdate,$enddate) {
                 if(!empty($mobile)){
                     $query->where('mobile', '=', $mobile);
                 } else if (!empty($username) ) {
                     $query->where('user_name','like','%' .$username. '%');
                 } else if(!empty($startdate) && !empty($enddate) ) {
                     $query->whereBetween('arrival_account',[$startdate, $enddate]);
                 }
             })->where($where_arr)->orderBy('id', 'desc')->paginate($pageSize);
         }
         $temp_arr = [];
         $list_data = [];
         foreach ($Shareholder_data as &$key) {
             $ascription = D('affiliation')->where('id',$key->ascription)->value('locality_name');
             $temp_arr['id'] = $key->id;
             $temp_arr['ascription'] = empty($ascription) ? '' : $ascription; //用户归属的运营中心
             $temp_arr['ascription_id'] = $key->ascription; //用户归属的运营中心
             $temp_arr['user_type'] = '股东用户';
             $temp_arr['user_name'] = $key->user_name;
             $temp_arr['sex'] = $key->sex;
             $temp_arr['Birthday'] = $key->Birthday;
             $temp_arr['mobile'] = $key->mobile;
             $temp_arr['share'] = $key->share;
             $temp_arr['bank_name'] = $key->bank_name;
             $temp_arr['opening_bank'] = $key->opening_bank;
             $temp_arr['account_name'] = $key->account_name; //账户名
             $temp_arr['bank_number'] = $key->bank_number; //银行卡号
             $temp_arr['id_card'] = $key->id_card; //身份证号
             $temp_arr['residence'] = $key->residence; //现居住地
             $temp_arr['address'] = $key->address; //身份证地址
             $temp_arr['total_funds'] = $key->total_funds;
             $temp_arr['created_at'] = empty($key->created_at) ? '' : $key->created_at;
             $temp_arr['updated_at'] = empty($key->updated_at) ? '': $key->updated_at;
             $temp_arr['ratio']  = $key->share/$TotalStock;
             $temp_arr['certificate_number'] = $key->certificate_number;
             $temp_arr['arrival_account'] = $key->arrival_account;
             $temp_arr['operator'] = $key->operator;//操作人
             $temp_arr['data_audit'] = $key->data_audit;
             $temp_arr['data_no_pass'] = $key->data_no_pass;
             $temp_arr['fund_audit'] = $key->fund_audit;
             $temp_arr['fund_no_pass'] = $key->fund_no_pass;
             $temp_arr['referrer'] = $key->referrer ?? '';
             $temp_arr['referrer_mobile'] = $key->referrer_mobile ?? '';
             $list_data[] = $temp_arr;
         }
         unset($key);
         return json_success('ok',['total'=>$Shareholder_data->total(),'totalPage' => $Shareholder_data->lastPage(), 'list' => $list_data]);
     }

    /**
     *
     * 审核不通过列表
     */
    public function AuditFailed()
    {
        $TotalStock = config('admin.TotalStock');//总注册资金
        $mobile = IT('mobile');//手机号码
        $username = IT('username');//用户名称
        $startdate = IT('startdate'); //开始时间
        $enddate = IT('enddate'); //结束时间
        $behavior = IT('behavior'); // 行为(资料不通过1、股份变更不通过2)
        $role_id = $this->user['role_id'];
        if($role_id == 5 ){
            $where_arr['user_binding'] = $this->user['id'];
        }
        $where_arr['status' ]  = 0;
        $pageSize = IT('pagesize') ?: 10;

        if($behavior == 2) {
            $select = ['audit_shareholders_funds.uid as uid','audit_shareholders_funds.id as id','shareholder.ascription','shareholder.user_name','shareholder.sex','shareholder.Birthday','shareholder.mobile','shareholder.share','shareholder.bank_name','shareholder.opening_bank','shareholder.account_name','shareholder.bank_number','shareholder.id_card',
                'shareholder.residence','shareholder.address','shareholder.created_at','shareholder.updated_at','shareholder.total_funds','shareholder.certificate_number','shareholder.arrival_account','shareholder.operator','shareholder.data_audit','shareholder.data_no_pass','shareholder.fund_audit','shareholder.fund_no_pass','shareholder.referrer','shareholder.referrer_mobile'];
            $Shareholder_data = AuditShareholdersFunds::where('audit_shareholders_funds.status', 2)
                ->where(function($query) use($mobile,$username,$startdate,$enddate) {
                    if(!empty($mobile)){
                        $query->where('shareholder.mobile', '=', $mobile);
                    } else if (!empty($username) ) {
                        $query->where('shareholder.user_name','like','%' .$username. '%');
                    } else if(!empty($startdate) && !empty($enddate) ) {
                        $query->whereBetween('shareholder.arrival_account',[$startdate, $enddate]);
                    }
                })->leftjoin('shareholder', 'audit_shareholders_funds.uid', '=','shareholder.id')
                ->select($select)
                ->orderBy('uid', 'desc')->paginate($pageSize);
        } else {
            $Shareholder_data = Shareholder::where(function($query) use($mobile,$username,$startdate,$enddate) {
                if(!empty($mobile)){
                    $query->where('mobile', '=', $mobile);
                } else if (!empty($username) ) {
                    $query->where('user_name','like','%' .$username. '%');
                } else if(!empty($startdate) && !empty($enddate) ) {
                    $query->whereBetween('arrival_account',[$startdate, $enddate]);
                }})
                ->where($where_arr)->where('data_audit', 2)->orderBy('id', 'desc')->paginate($pageSize);
        }

        $temp_arr = [];
        $list_data = [];
        foreach ($Shareholder_data as &$key) {
            /*if ( $key->data_audit=2 && $key->fund_audit=1){
                $audit_change =0;
                $reason = !empty($key->data_no_pass) ? $key->data_no_pass : '' ;
            }*/
            if($behavior == 1) {
                $audit_change = 1;
                $reason = !empty($key->data_no_pass) ? $key->data_no_pass : '' ;
            }
            /*if ($key->data_audit=1 && $key->fund_audit=2){
                $audit_change =0;
                $reason = !empty($key->data_no_pass) ? $key->data_no_pass : '' ;
            }*/
            /*if ($key->stock_audit == 2){
                $audit_change = 1;
                $reason = !empty($key->stock_no_pass) ? $key->stock_no_pass :'';
            }*/
            if($behavior == 2) {
                $audit_change = 2;
                $reason = !empty($key->stock_no_pass) ? $key->stock_no_pass :'';
            }
            $temp_arr['audit_change'] = $audit_change;
            $ascription = D('affiliation')->where('id',$key->ascription)->value('locality_name');
            $temp_arr['id'] = $key->id;
            $temp_arr['ascription'] = empty($ascription) ? '' : $ascription; //用户归属的运营中心
            $temp_arr['user_type'] = '股东用户';
            $temp_arr['user_name'] = $key->user_name;
            $temp_arr['sex'] = $key->sex;
            $temp_arr['Birthday'] = $key->Birthday;
            $temp_arr['mobile'] = $key->mobile;
            $temp_arr['share'] = $key->share;
            $temp_arr['bank_name'] = $key->bank_name;
            $temp_arr['opening_bank'] = $key->opening_bank;
            $temp_arr['account_name'] = $key->account_name; //账户名
            $temp_arr['bank_number'] = $key->bank_number; //银行卡号
            $temp_arr['id_card'] = $key->id_card; //身份证号
            $temp_arr['residence'] = $key->residence; //现居住地
            $temp_arr['address'] = $key->address; //身份证地址
            $temp_arr['total_funds'] = $key->total_funds;
            $temp_arr['created_at'] = empty($key->created_at) ? '' : $key->created_at;
            $temp_arr['updated_at'] = empty($key->updated_at) ? '': $key->updated_at;
            $temp_arr['ratio']  = $key->share/$TotalStock;
            $temp_arr['certificate_number'] = $key->certificate_number;
            $temp_arr['arrival_account'] = $key->arrival_account;
            $temp_arr['operator'] = $key->operator;//操作人
            $temp_arr['reason'] = empty($reason) ? '' : $reason;
            $temp_arr['referrer'] = $key->referrer ?? '';
            $temp_arr['referrer_mobile'] = $key->referrer_mobile ?? '';
            $list_data[] = $temp_arr;
        }
        unset($key);
        return json_success('ok',['total'=>$Shareholder_data->total(),'totalPage' => $Shareholder_data->lastPage(), 'list' => $list_data]);
     }
    /**
     * @desc 审核股东股份变更
     */
     public function AuditShareholderStock()
     {
         $id = IT('id',true,'请选择审核的股东');
         $stock_audit =IT('audit_status',true,'请选择审核股东股份变更的状态');
         $reason =IT('reason');
         $where_arr['id'] = $id ;
         $where_arr['status'] = 0;
         $audit_user_data = AuditShareholdersFunds::where($where_arr)->first();
         $check = Shareholder::where(['id'=>$audit_user_data->uid])->first();
         if(!$check){
             return json_error('用户不存在');
         }
         if(!$audit_user_data){
             return json_error('该用户变更记录不存在');
         }

         if(!in_array($stock_audit,[1,2])){
             return json_error('参数不正确');
         }
         if($stock_audit == 2 && empty($reason)){
             return json_error('请填写不通过的原因');
         }
         //审核通过，将记录写到股份变更日志 股东审核记录表数据清零
         if($stock_audit == 1) {
             $arrival_account =IT('arrival_account',true,'请输入资金到账时间');
             // 追加股份、追加金额
             if($audit_user_data->append_share > 0 ){
                 $append_share = $audit_user_data->append_share;
                 $dilution_share = $audit_user_data->dilution_share;
                 $Surplus = $check->share + $append_share;
                 $total_funds = $check->total_funds + $audit_user_data->append_money;
             }else{
                 $append_share= $audit_user_data->append_share;
                 $dilution_share = $audit_user_data->dilution_share;
                 $Surplus = $check->share - $dilution_share;
                 $total_funds = $check->total_funds;
             }
             $Shareholder_log = [
                 'shareholder_id' => $check->id,
                 'total_number' => $check->share,
                 'dilution' => $dilution_share,
                 'Surplus' =>$Surplus ,
                 'append_share' =>$append_share ,
                 'dilution_share' =>$dilution_share ,
                 'time' => time2date(),
             ];
             //将信息，写入到股权变更日志表
             $update_log= ShareholderLog::insert($Shareholder_log);
             if($update_log){
                 $shareholder_data =[
                     'share'=>$Surplus,
                     'arrival_account'=>$arrival_account,
                     'stock_audit'=> $stock_audit,
                     'total_funds' => $total_funds
                 ];
                 $audit_rs = Shareholder::where(['id'=>$check->id,'status'=> 0])->update($shareholder_data);
                 //审核记录改为通过
                 AuditShareholdersFunds::where($where_arr)->update(['status'=>$stock_audit]);
             }
         }
         if($stock_audit == 2 ){
             $audit_rs = Shareholder::where(['id'=>$check->id,'status'=> 0])->update(['stock_audit'=> $stock_audit,'stock_no_pass'=>$reason]);
             AuditShareholdersFunds::where('id',$id)->update(['status'=>$stock_audit]);
         }
         if(!$audit_rs){
             return json_error('操作失败');
         }
         (new Log)->add($this->user, '审核股东id-' . $id.'变更股份'.$check->user_name );
         return json_success('ok');
     }

    /**
     * @desc 审核股东资料
     */
    public function AuditShareholderData()
    {
        $id = IT('id', true, '请选择审核的股东');
        $data_audit = IT('audit_status', true, '请选择审核资料的状态');
        $certificate_number = IT('certificate_number');
        if(!in_array($data_audit, [1 , 2])) {
            return json_error('审核状态异常');
        }

        $shareholder_data = ['data_audit' => $data_audit];
        // 审核通过
        if($data_audit == 1) {
            $shareholder_data['data_no_pass'] = ''; // 重新审核，清除上一次的审核不通过的原因
            if(!empty($certificate_number)) {
                $shareholder_data['certificate_number'] = $certificate_number;
                $is_record = Shareholder::select(['id'])->where([['id', '!=', $id], ['certificate_number', '=', $certificate_number], ['status', '=', 0]])->first();
                if($is_record) {
                    return json_error('证书编号已存在');
                }
            }
        }
        // 审核不通过
        if($data_audit == 2) {
            $shareholder_data['data_no_pass'] = IT('reason', true, '审核不通过原因不能为空');
            $shareholder_data['data_audit'] = 2;
            if(strlen($shareholder_data['data_no_pass']) > 255) {
                return json_error('审核不通过原因不能超过255个字符');
            }
        }

        $shareholder_info = Shareholder::select(['id', 'stock_audit', 'fund_audit', 'data_audit', 'mobile','ascription'])->where(['id' => $id, 'status' => 0])->first();
        if(!$shareholder_info) {
            return json_error('股东数据不存在');
        }

        if($shareholder_info->data_audit == 1) {
            return json_error('已经审核通过，不能重新审核');
        }

        $rs = Shareholder::where(['id' => $id])->update($shareholder_data);
        if(!$rs) {
            return json_error('审核失败');
        }

        (new Log)->add($this->user, '审核了股东，id-' . $id.'的资料');
        // 资金已审核通过
        if(($shareholder_info->fund_audit == 1) && ($data_audit == 1)) {
            User::where(['mobile' =>$shareholder_info->mobile])->update(['role' => 1,'ascription'=>$shareholder_info->ascription ]); // 修改用户股东身份
            (new Log)->add($this->user, '审核了股东，id-' . $id.'的资料，并且成为股东');
        }
        return json_success('ok');
    }


    /**
     * @desc 审核股东资金到账
     * @return array
     */
    public function AuditShareholderFund()
    {
        $id = IT('id', true, '请选择审核的股东');
        $fund_audit = IT('audit_status', true, '请选择审核资金的状态');
        if(!in_array($fund_audit, [1 , 2])) {
            return json_error('审核状态异常');
        }

        $shareholder_data = ['fund_audit' => $fund_audit];
        // 审核通过
        if($fund_audit == 1) {
            $shareholder_data['arrival_account'] = IT('fund_arrival_time', true, '资金到账时间不能为空');
            if(!strtotime($shareholder_data['arrival_account'])) {
                return json_error('资金到账时间格式不正确');
            }
            $shareholder_data['fund_no_pass'] = ''; // 重新审核，清除上一次的审核不通过的原因
        }
        // 审核不通过
        if($fund_audit == 2) {
            $shareholder_data['fund_no_pass'] = IT('reason', true, '审核不通过原因不能为空');
            if(strlen($shareholder_data['fund_no_pass']) > 255) {
                return json_error('审核不通过原因不能超过255个字符');
            }
        }

        $shareholder_info = Shareholder::select(['id', 'stock_audit', 'data_audit', 'fund_audit', 'mobile'])->where(['id' => $id, 'status' => 0])->first();
        if(!$shareholder_info) {
            return json_error('股东数据不存在');
        }

        if($shareholder_info->fund_audit == 1) {
            return json_error('已经审核通过，不能重新审核');
        }

        $rs = Shareholder::where(['id' => $id])->update($shareholder_data);
        if(!$rs) {
            return json_error('审核失败');
        }
        (new Log)->add($this->user, '审核了股东，id-' . $id.'的资金到账');
        // 数据已审核
        if(($shareholder_info->data_audit == 1) && ($fund_audit == 1)) {
            User::where(['mobile' =>$shareholder_info->mobile])->update(['role'=>1]); // 修改用户股东身份
            (new Log)->add($this->user, '审核了股东，id-' . $id.'的资金到账,并且成为股东');
        }
        return json_success('ok');
    }

    /**
     * @return array
     * 股东资料未通过详情
     */
    public function NoDetailsPassed(){

        $behavior = IT('behavior'); // 行为(资料不通过1、股份变更不通过2)
        $TotalStock = config('admin.TotalStock');//总注册资金
       // $role_id = $this->user['role_id'];
        $id = IT('id',true,'请输入用户id');
        if($behavior == 1){
            $data = Shareholder::where('id','=',$id)->first();
        }
        if($behavior == 2){
            $data = AuditShareholdersFunds::where('id','=',$id)->first();
        }

        if($behavior == 1){
            $audit_change = 1;
        }
        if($behavior == 2 ){
            $audit_change =2;
        }
        $data->audit_change = $audit_change;
        $data->ratio = $data['share']/$TotalStock;
        $data->ascription =  D('affiliation')->where('id',$data['ascription'])->value('locality_name');
        if($data->stock_audit == 2 ){
            $check_audit = AuditShareholdersFunds::where('uid','=',$id)->first();
            if(!$check_audit){
                return json_error('此用户暂无变更记录');
            }
            $data->append_share = AuditShareholdersFunds::where('uid',$id)->value('append_share');
            $data->dilution_share = AuditShareholdersFunds::where('uid',$id)->value('dilution_share');
            $data->append_money = AuditShareholdersFunds::where('uid',$id)->value('append_money');
        }else{
            $shareholder_agree_img_list = [];
            if($data->shareholder_agree_img) {
                $shareholder_agree_img_list = explode(',', $data->shareholder_agree_img);
                foreach($shareholder_agree_img_list as &$shareholder_agree_img) {
                    $shareholder_agree_img = file_get_contents(getSignUrl($shareholder_agree_img));
                }
            }
            $data->shareholder_agree_img = $shareholder_agree_img_list;
        }
        return json_success('ok', $data);
    }




    /**
     *推广会员列表
     *
     */
     public function MembershipList(Request $request){
         $page = intval($request->input('page')) ?: 1;
         $page = $page - 1;
         $pageSize = IT('pagesize') ?: 10;
         $name = $request->input('name');
         $mobile = $request->input('mobile');
         $member_ascription = $this->user;
         $where=[];
         if (isset($name)) {
             $where[] = ['name', 'like', '%' . $name . '%'];
         }elseif(isset($mobile)){
             $where[] = ['mobile', 'like', '%' . $mobile . '%'];
         }
         if($member_ascription['permissions'] !=='*'){
             $where[] =['ascription','=',$member_ascription['city_of_origin'] ];
         }
         $total =  MemberShip::where($where)->where('status','=',0)->count();
         $totalPage = ceil($total / $pageSize);
         $menber = MemberShip::where($where)->where('status','=',0)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get(['id','name','mobile','number','avatar','sex','bank_number','admission_fee','term_validity','ascription','time_admission']);
         foreach ($menber as $k){
             $k->ascription  = D('affiliation')->where('id',$k->ascription)->value('locality_name');
             $k->ascription_id = $k->ascription;
             $k->menber_type = "推广会员";
             $k->term_validity="永久有效";
             $k->avatar= getSignUrl($k->avatar);
             $k->created_at = !empty($k->time_admission) ? substr($k->time_admission,0,10) : '';
         }
         unset($k);
         return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $menber]);
     }

    /**
     * @return array
     * 添加会员
     */
    public function  AddMember(){
        $name = IT('name',true,'亲输入姓名');
        $sex = IT('sex');
        $mobile = IT('mobile',true,'请输入手机号码');
        $number = IT('number',true,'请输入会员编号');
        $admission_fee = IT('admission_fee');
        $time_admission = IT('time_admission',true,'请输入入会时间');
        $bank_number = IT('bank_number');
        $term_validity = IT('term_validity');
        $ascription = IT('ascription');
        $member_data = MemberShip::where(['mobile'=>$mobile ,'status'=> 0])->first();
        if($member_data){
            return json_error('手机号码已存在');
        }
        $data = [
            'name' =>$name,
            'mobile' =>$mobile,
            'number' =>$number,
            'sex' =>$sex,
            'bank_number' =>$bank_number,
            'admission_fee' =>$admission_fee,
            'term_validity' =>$term_validity,
            'ascription' =>$ascription,
            'created_at' => time2date(),
            'time_admission' => $time_admission
        ];
        $insert_date = MemberShip::insertGetId($data);
        if($insert_date){
            //TODO 添加成功，修改users 表中的会员状态
            User::where('mobile','=',$mobile)->update(['membership'=>1]);
            $check_mobile = User::where(['mobile'=>$mobile, 'status'=>1])->first();
            if($check_mobile){
                MemberShip::where('mobile','=',$mobile)->update(['avatar' =>$check_mobile->avatar]);
            }
            //修改会员归属地
            if($check_mobile->ascription==0){
                User::where('mobile','=',$mobile)->update(['ascription'=>$ascription]);
            }
            (new Log)->add($this->user, '添加了推广会员，id为-' . $insert_date );
            return json_success('ok');
        }else{
            return json_error('添加失败!');
        }
    }

    /**
     * @return array
     * 推广会员详情
     */
     public function MembereDtails(){
         $id=IT('id',true,'请输入ID');
         $data= MemberShip::where('id','=',$id)->first(['id','name','mobile','sex','number','avatar','bank_number','admission_fee','created_at','term_validity','ascription','time_admission']);
         if (!$data){
           return json_success('会员不存在');
         }
         $affiliation = D('affiliation')->where('id',$data['ascription'])->value('locality_name');
         $data['ascription_id'] = (int)$data['ascription'];
         $data['ascription'] = !empty($affiliation) ? $affiliation : '';
         $data['created_at'] =  !empty($data['time_admission']) ? $data['time_admission'] :'';
         return json_success('ok',$data);
     }
    /**
     * @return array
     * 推广会员修改
     */

     public function EditMember(){
         $id = IT('id',true,'请输入会员ID');
         $check_user = MemberShip::where('id','=',$id)->first();
         $name = IT('name');
         $sex = IT('sex');
         $mobile = IT('mobile');
         $number = IT('number');
         $admission_fee = IT('admission_fee');
         $time_admission = IT('time_admission');
         $bank_number = IT('bank_number');
         $term_validity = IT('term_validity');
         $ascription = IT('ascription');
         if(!$check_user){
             return json_error('暂无此用户');
         }
         if($name && ($name!== $check_user->name)){
           $update_user['name'] = $name ;
         }
         if($sex && ($sex !== $check_user->sex)){
             $update_user['sex']=$sex;
         }
         if($mobile && ($mobile !== $check_user->mobile)){
             $check_mobile = MemberShip::where(['mobile' =>$mobile,'status'=>0])->first();
             if($check_mobile){
                 return json_error('手机号码已存在');
             }
             User::where('mobile',$mobile)->update(['membership'=>1]);
             $update_user['mobile']=$mobile;
         }
         if($number && ($number!== $check_user->number)){
             $update_user['number']=$number;
         }
         if($admission_fee && ($admission_fee!== $check_user->admission_fee)){
             $update_user['admission_fee']=$admission_fee;
         }
         if( $time_admission && ($time_admission !== $check_user->time_admission) ){
             $update_user['time_admission']=$time_admission;
         }
         if( $bank_number && ($bank_number!== $check_user->bank_number)){
             $update_user['bank_number']=$bank_number;
         }
         if($term_validity && ($term_validity!== $check_user->term_validity)){
             $update_user['term_validity']=$term_validity;
         }
         if($ascription && ($ascription!== $check_user->ascription)){
             $update_user['ascription']=$ascription;
         }
         $update_user['updated_at'] = time2date();
         $success_data =MemberShip::where('id','=',$id)->update($update_user);
         if($success_data){
              $check_mobile = User::where(['mobile'=>$mobile, 'status'=>1])->first();
              if($check_mobile){
                   MemberShip::where('mobile','=',$mobile)->update(['avatar' =>$check_mobile->avatar]);
              }
             (new Log)->add($this->user, '修改推广会员，id为-' . $id );
             return json_success('ok');
         }elseif(!$success_data){
             return json_error('请填写，你要修改的内容');
         }else{
             return json_error('修改失败');
         }
     }

    /**
     * 推广会员删除
     */
     public function DelMember(){
         $id = IT('id',true,'请输入ID');
         $member_data = MemberShip::where('id','=',$id)->first();
         if(!$member_data){
              return json_error('此会员不存在');
         }
         $del_date = MemberShip::where('id','=',$id)->update(['status'=>1]);
         if($del_date){
             //TODO 删除成功，修改users 表中的会员状态
             User::where('mobile','=',$member_data->mobile)->update(['membership'=> 0]);
             (new Log)->add($this->user, '删除了推广会员，id为-' .$id );
             return json_success('ok');
         }else{
            return json_error('删除失败');
         }
     }

    /**
     * @desc 重新审核股份变更不通过
     * @return array
     */
     public function audit_shareholders_alteration()
     {
         $id = IT('id',true,'请输入ID');
         $data['append_share'] = IT('append_share');
         $data['dilution_share'] = IT('dilution_share');
         $data['append_money'] = IT('append_money');

         if($data['append_share'] > 0) {
             if($data['dilution_share'] > 0) {
                 return json_error('稀释股份异常');
             }

             if($data['append_money'] == 0) {
                 return json_error('追加金额异常');
             }
         }

         $shareholders_funds_info = AuditShareholdersFunds::where('id','=',$id)->first();
         $data['updated_at'] = time2date();
         $data['status'] = 0;
         AuditShareholdersFunds::where(['id' => $id])->update($data);
         Shareholder::where(['id' => $shareholders_funds_info->uid])->update(['stock_audit' => 0]);

         return json_success('ok');
     }
}